package com.limou.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.limou.constants.SystemConstants;
import com.limou.domain.ResponseResult;
import com.limou.domain.dto.AddArticleDto;
import com.limou.domain.entity.Article;
import com.limou.domain.entity.ArticleTag;
import com.limou.domain.entity.Category;
import com.limou.domain.vo.*;
import com.limou.mapper.ArticleMapper;
import com.limou.service.ArticleService;
import com.limou.service.ArticleTagService;
import com.limou.service.ArticleVoService;
import com.limou.service.CategoryService;
import com.limou.utils.BeanCopyUtils;
import com.limou.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 查询热门文章
     *
     * @return
     */
    @Override
    public ResponseResult hotArticleList() {

        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        // 1、必须是正式文章；2、按照浏览量降序排序；3、查询10条数据最多
        wrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        wrapper.orderByDesc(Article::getViewCount);

        Page<Article> page = new Page(1, 10);
        page(page, wrapper);

        List<Article> articleList = page.getRecords();

        List<HotArticleVo> hotArticleVoList = BeanCopyUtils.copyBeanList(articleList, HotArticleVo.class);

        return ResponseResult.okResult(hotArticleVoList);
    }

    /**
     * 分页查询文章
     *
     * @param pageNum    页号
     * @param pageSize   页面大小
     * @param categoryId 分类id
     * @return
     */
    @Override
    public ResponseResult articleList(Integer pageNum, Integer pageSize, Long
            categoryId) {
        //查询条件
        LambdaQueryWrapper<Article> lambdaQueryWrapper = new
                LambdaQueryWrapper<>();
        // 如果 有categoryId 就要 查询时要和传入的相同【默认加载的时候不传入分类id】
        lambdaQueryWrapper.eq(Objects.nonNull(categoryId) && categoryId > 0
                , Article::getCategoryId, categoryId);
        // 状态是正式发布的
        lambdaQueryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL)
        ;
        // 对isTop进行降序
        lambdaQueryWrapper.orderByDesc(Article::getIsTop);

        // 分页查询
        Page<Article> page = new Page<>(pageNum, pageSize);
        page(page, lambdaQueryWrapper);

        List<Article> articleList = page.getRecords();

        //articleId去查询articleName进行设置
        for (Article article : articleList) {
            Category category = categoryService.getById(article.getCategoryId());
            article.setCategoryName(category.getName());
        }

        //封装查询结果
        List<ArticleListVo> articleListVos =
                BeanCopyUtils.copyBeanList(page.getRecords(), ArticleListVo.class);
        PageVo pageVo = new PageVo(articleListVos, page.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    /**
     * 查询文章详情
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult getArticleDetail(Long id) {
        //根据id查询文章
        Article article = getById(id);

        // 从redis中获取viewCount
        Integer viewCount = redisCache.getCacheMapValue("article:viewCount",
                id.toString());
        article.setViewCount(viewCount.longValue());

        //转换成VO
        ArticleDetailVo articleDetailVo = BeanCopyUtils.copyBean(article,
                ArticleDetailVo.class);
        //根据分类id查询分类名
        Long categoryId = articleDetailVo.getCategoryId();
        Category category = categoryService.getById(categoryId);
        if (category != null) {
            articleDetailVo.setCategoryName(category.getName());
        }
        //封装响应返回
        return ResponseResult.okResult(articleDetailVo);
    }

    /**
     * 更新浏览量
     * @param id
     * @return
     */
    @Override
    public ResponseResult updateViewCount(Long id) {
        //更新redis中对应 id的浏览量
        redisCache.incrementCacheMapValue("article:viewCount",id.toString(),1);
        return ResponseResult.okResult();
    }


    @Autowired
    private ArticleTagService articleTagService;

    @Autowired
    private ArticleVoService articleVoService;

    /**
     * 增加博客文章
     * @param articleDto
     * @return
     */
    @Override
    @Transactional
    public ResponseResult add(AddArticleDto articleDto) {
        //添加 博客
        ArticleVo articlevo = BeanCopyUtils.copyBean(articleDto, ArticleVo.class);
        articleVoService.save(articlevo);

        List<ArticleTag> articleTags = articleDto.getTags().stream()
                .map(tagId -> new ArticleTag(articlevo.getId(), tagId))
                .collect(Collectors.toList());

        //添加 博客和标签的关联
        articleTagService.saveBatch(articleTags);
        return ResponseResult.okResult();
    }
}


